Skip to main content

Testing for NaN using isNaN()

window.isNaN()

The global function isNaN() can be used to check if a certain value or expression evaluates to NaN. This function (in short) first checks if the value is a number, if not tries to convert it (*), and then checks if the resulting value is NaN. For this reason, this testing method may cause confusion.

(*) The "conversion" method is not that simple, see ECMA-262 18.2.3 for a detailed explanation of the algorithm.

These examples will help you better understand the isNaN() behavior:

isNaN(NaN);  // true
isNaN(1); // false: 1 is a number
isNaN(-2e-4);
isNaN(Infinity);
isNaN(true);
isNaN(false);
isNaN(null);
isNaN("");
isNaN(" ");
isNaN("45.3");
isNaN("1.2e3");
isNaN("Infinity");
isNaN(new Date);
isNaN("10$");
isNaN("hello");
isNaN(undefined);
isNaN();
isNaN(function(){});
isNaN({});
isNaN([1, 2]);


// false: -2e-4 is a number (-0.0002) in scientific notation
// false: Infinity is a number
// false: converted to 1, which is a number
// false: converted to 0, which is a number
// false: converted to 0, which is a number
// false: converted to 0, which is a number
// false: converted to 0, which is a number
// false: string representing a number, converted to 45.3
// false: string representing a number, converted to 1.2e3
// false: string representing a number, converted to Infinity
// false: Date object, converted to milliseconds since epoch
// true : conversion fails, the dollar sign is not a digit
// true : conversion fails, no digits at all
// true : converted to NaN
// true : converted to NaN (implicitly undefined)
// true : conversion fails
// true : conversion fails
// true : converted to "1, 2", which can't be converted to a number